package com.sptus.web.controller.admin;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sptus.common.core.controller.BaseController;
import com.sptus.common.core.domain.AjaxResult;
import com.sptus.framework.service.BaseCommonService;
import com.sptus.framework.utils.CustomSortExample;
import com.sptus.system.domain.DevDictionaries;
import com.sptus.system.domain.DevInfoMsg1History;
import com.sptus.system.domain.DeviceModel;
import com.sptus.system.domain.Equipment;
import com.sptus.system.domain.vo.AppInfo;
import com.sptus.web.config.DataLoaderConfig;
import com.sptus.web.entity.SptUser;
import com.sptus.system.service.ISptDevLogService;
import com.sptus.web.service.impl.CloudEquipmentServiceImpl;
import com.sptus.web.service.impl.DevDictionariesServiceImpl;
import com.sptus.web.util.DevSqlUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("/sys/deviceManage")
@Api(tags="设备管理")
public class DeviceListController  extends BaseController {
    @Autowired
    CloudEquipmentServiceImpl equipmentService;

    @Autowired
    DevDictionariesServiceImpl devDictionariesService;

    @Autowired
    private ISptDevLogService sptDevLogService;

    @Resource
    private BaseCommonService baseCommonService;

    @Autowired
    private JdbcTemplate jdbcTemplate;
    @GetMapping("getDeviceList")
    @ApiOperation("获取设备列表")
    public AjaxResult getDeviceList(DeviceModel deviceModel) {
        HashMap<String, Object> list= equipmentService.selectListPage(deviceModel);
        return AjaxResult.success(list);
    }

    @GetMapping("getDeviceUpgrade")
    @ApiOperation("获取设备更新版本")
    public AjaxResult getDeviceUpgrade(DeviceModel deviceModel) {
        HashMap<String, Object> upgrade= equipmentService.getDeviceUpgrade(deviceModel);
        return AjaxResult.success(upgrade);
    }

    @GetMapping("getDeviceState")
    @ApiOperation("获取设备充电状态")
    public AjaxResult getDeviceState(DeviceModel deviceModel) {
        HashMap<String, Object> upgrade= equipmentService.getDeviceState(deviceModel);
        return AjaxResult.success(upgrade);
    }


    @ApiOperation(value="设备字典详情数据", notes="设备字典详情数据")
    @GetMapping(value = "/devDictionaries")
    public AjaxResult devDictionaries() {
        LambdaQueryWrapper<DevDictionaries> devDictionariesLambdaQueryWrapper = new LambdaQueryWrapper<>();
        devDictionariesLambdaQueryWrapper.eq(DevDictionaries::getRelevanceTable,"dev_info_msg0");
        List<DevDictionaries> devDictionaries = devDictionariesService.getBaseMapper().selectList(devDictionariesLambdaQueryWrapper);
        devDictionaries = CustomSortExample.sort(devDictionaries);
        return AjaxResult.success("获取成功", devDictionaries);
    }

    @GetMapping("/getHistoryDataInfo")
    @ApiOperation(value="获取统计数据接口", notes="获取历史数据接口")
    public AjaxResult getHistoryData(AppInfo appInfo, SptUser sptUser) throws ParseException {
        return   devDictionariesService.getHistoryData( appInfo, sptUser);
    }
    @PreAuthorize("@ss.hasPermi('device:Parameter')")
    @GetMapping("/setDeviceUpgrade")
    @ApiOperation(value="升级设备更新版本", notes="获取历史数据接口")
    public AjaxResult setDeviceUpgrade(AppInfo appInfo) throws ParseException {
        LambdaQueryWrapper<Equipment> equipmentLambdaQueryWrapper = new LambdaQueryWrapper<>();
        equipmentLambdaQueryWrapper.eq(Equipment::getSn,appInfo.getSn());
        Equipment equipment = equipmentService.getBaseMapper().selectOne(equipmentLambdaQueryWrapper);
        if (StringUtils.isEmpty(equipment)) {
            return AjaxResult.error("Please enter correctly sn");
        }
        if (!equipment.getStatus().equals("1")) {
            return AjaxResult.error("Device Offline");
        }
        ArrayList<DevDictionaries> devs = appInfo.getDevs();
        //设置参数
        if (StringUtils.isEmpty(equipment.getMac())) {
            return AjaxResult.error("Device Offline");
        }
        String version ="";
        DevDictionaries devDictionaries1 = new DevDictionaries();
        if(appInfo.getValue().equals("0")){
            version= DataLoaderConfig.getGlobalData().get("spt.rds.dsp");

        }else if(appInfo.getValue().equals("9")){
            version= DataLoaderConfig.getGlobalData().get("spt.rds.remote");

        }
            devDictionaries1.setName(appInfo.getCode());
            devDictionaries1.setValue(version);
            devDictionaries1.setSN(appInfo.getSn());
            devDictionaries1.setCode( appInfo.getCode());
            sptDevLogService.saveDevSetUpdate(devDictionaries1,appInfo.getValue());
            DevSqlUtil.setDevParameters(appInfo.getCode(), appInfo.getValue(), equipment.getMac(),appInfo.getSn(),baseCommonService,"pc:-> "+getUserId(),getUsername());
            return AjaxResult.success();
    }

    @GetMapping("/getDevClassify")
    @ApiOperation(value="设备分类", notes="获取历史数据接口")
    public AjaxResult getDevClassify(AppInfo appInfo, SptUser sptUser) throws ParseException {
        ArrayList<HashMap<String, Object>> type=  equipmentService.getDevTypeNum();

        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("3800B",0);
        stringObjectHashMap.put("3800A",0);
        stringObjectHashMap.put("3800C",0);
        stringObjectHashMap.put("3800D",0);
        stringObjectHashMap.put("3800E",0);
        for (HashMap<String, Object> hashMap : type) {
           if( stringObjectHashMap.containsKey(hashMap.get("type"))){
               stringObjectHashMap.put(hashMap.get("type")+"",hashMap.get("num"));
           }
        }
        return AjaxResult.success(stringObjectHashMap);
    }



//    @AutoLog(value = "获取单个设备数据")
//    @ApiOperation(value="设备详情数据", notes="设备详情数据")
//    @GetMapping(value = "/equipmentDataInfo")
//    public Result<Object> equipmentDataInfo( DevDictionaries dev) {
//        LambdaQueryWrapper<DevDictionaries> devDictionariesLambdaQueryWrapper = new LambdaQueryWrapper<>();
//        devDictionariesLambdaQueryWrapper.in(!ObjectUtils.isEmpty(dev.getIds()),DevDictionaries::getId, dev.getIds());
//        devDictionariesLambdaQueryWrapper.eq(DevDictionaries::getState, "1");
//        List<DevDictionaries> devDictionaries = devDictionariesService.getBaseMapper().selectList(devDictionariesLambdaQueryWrapper);
//        //通过字典获取设备数据
//        AppInfo appInfo = new AppInfo();
//        appInfo.setSn(dev.getSN());
//        devDictionaries = DevSqlUtil.DevDataSql(devDictionaries, jdbcTemplate, dev.getSN());
//        Result<Object> code = Result.OK("获取成功");
//        code.setMessage("");
//        code.setResult(devDictionaries);
//        return code;
//    }

//    @AutoLog(value = "设备详情数据")
    @ApiOperation(value="设备详情数据", notes="设备详情数据")
    @GetMapping(value = "/equipmentDataInfo")
    public AjaxResult equipmentDataInfo(DevDictionaries dev) {
        LambdaQueryWrapper<DevDictionaries> devDictionariesLambdaQueryWrapper = new LambdaQueryWrapper<>();
//        devDictionariesLambdaQueryWrapper.in(!ObjectUtils.isEmpty(dev.getIds()),DevDictionaries::getId, dev.getIds());
        devDictionariesLambdaQueryWrapper.eq(DevDictionaries::getState, "1");
        List<DevDictionaries> devDictionaries = devDictionariesService.getBaseMapper().selectList(devDictionariesLambdaQueryWrapper);
        //通过字典获取设备数据
        AppInfo appInfo = new AppInfo();
        appInfo.setSn(dev.getSN());
        devDictionaries = DevSqlUtil.DevDataSql(devDictionaries, jdbcTemplate, dev.getSN());
        return AjaxResult.success("获取成功", devDictionaries);
    }


//    @AutoLog(value = "设备电池详情数据")
    @ApiOperation(value="设备电池详情数据", notes="设备电池详情数据")
    @GetMapping(value = "/equipmentBatteryDataInfo")
    public AjaxResult equipmentBatteryDataInfo(DevDictionaries  dev) {
        AppInfo appInfo = new AppInfo();
        appInfo.setSn(dev.getSN());
        HashMap<String, ArrayList<DevDictionaries>> allData = devDictionariesService.getAllData(appInfo);
        return AjaxResult.success("获取成功", allData);
    }

    @PostMapping("/getHistoryData")
    @ApiOperation(value="获取数据统计接口", notes="获取历史数据接口")
    public AjaxResult getHistoryData(@RequestBody AppInfo appInfo) throws ParseException {
        if(StringUtils.isEmpty(appInfo.getEndTime())&& !StringUtils.isEmpty(appInfo.getStartTime())){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date parse = sdf.parse(appInfo.getStartTime());
            long time = parse.getTime();
            long end= time+24*60*60*1000;
            String format1 = sdf.format(end);
            appInfo.setEndTime(format1);
        }
        if(appInfo.getIds().size() == 0 || StringUtils.isEmpty(appInfo.getStartTime())|| StringUtils.isEmpty(appInfo.getEndTime())|| StringUtils.isEmpty(appInfo.getSn())){
            return AjaxResult.success("参数未输入");
        }
        LambdaQueryWrapper<DevDictionaries> devDictionariesLambdaQueryWrapper = new LambdaQueryWrapper<>();
        devDictionariesLambdaQueryWrapper.in(DevDictionaries::getId, appInfo.getIds());
//        devDictionariesLambdaQueryWrapper.eq(DevDictionaries::getState, "1");
        List<DevDictionaries> devDictionaries = devDictionariesService.getBaseMapper().selectList(devDictionariesLambdaQueryWrapper);
        for (DevDictionaries devDictionary : devDictionaries) {
//			 devDictionary.setAnalysis("");
            devDictionary.setRelevanceTable(devDictionary.getRelevanceTable()+"_history");

        }
//		     ArrayList<String> strings = new ArrayList<>();
        DevDictionaries devDictionariesTime = new DevDictionaries();
        devDictionariesTime.setCode("DATE_FORMAT(create_time,'%y/%m/%e %H:%i')");
        devDictionariesTime.setRelevanceTable("dev_info_msg0_history");
        devDictionaries.add(devDictionariesTime);
        devDictionaries = DevSqlUtil.DevDataHistorySql(devDictionaries, appInfo.getStartTime(), appInfo.getEndTime(), jdbcTemplate, appInfo.getSn());
        return AjaxResult.success(devDictionaries);
    }

    @GetMapping("/getHistoryDataSetInfo")
    @ApiOperation(value="获取历史设置数据列表", notes="获取历史数据接口")
    public AjaxResult getHistoryDataSetInfo(AppInfo appInfo, @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                                HttpServletRequest req) {
        String sn = appInfo.getSn();
        QueryWrapper<DevInfoMsg1History>   queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("dev_info_msg1_history.sn",sn);

        queryWrapper.between(!ObjectUtils.isEmpty(appInfo.getStartTime()),"dev_info_msg1_history.create_time",appInfo.getStartTime(),appInfo.getEmail());
        Page<DevInfoMsg1History> page = new Page<DevInfoMsg1History>(pageNo, pageSize);
        IPage<HashMap<String, Object>> pageList = equipmentService.getHistoryDataSetInfoPage(page, queryWrapper);
        return AjaxResult.success(pageList);
    }
}
